package com.ljf.game.event;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.ljf.game.WebsocketManager;
import com.ljf.game.schedule.HeartBeatSchedule;
import org.springframework.web.socket.WebSocketSession;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 描述 :
 *
 {
 "EVENT_CLASS":"ROOM_HEART_BEAT"
 }
 * <p>
 * 版本     作者     时间      内容
 * 1.0      lijinfeng       2025-04-29 14:32     create
 */
public class RoomHeartBeatEvent extends AbstractEvent {


    public void run(WebSocketSession session,String text) {

        JSONObject jsonObject =  JSON.parseObject(text);
        String homeowner = jsonObject.get("HOME_OWNER").toString();

        String username = WebsocketManager.getUsername(session);
        ConcurrentHashMap<String, WebSocketSession> roomMap =  WebsocketManager.groupGet(homeowner);

        HashMap<String, Object> hashMap = EventManager.getResultMap(text);

        if(null == roomMap || roomMap.isEmpty()){
            WebsocketManager.sendMessage(session, hashMap, "房间 [" + homeowner + "] 不存在");
            return;
        }
        boolean inRoom = false;
        ArrayList<String> members = new ArrayList<>();
        for (Map.Entry<String, WebSocketSession> entry : roomMap.entrySet()) {
            members.add(entry.getKey());
            if (username.equals(entry.getKey())){
                inRoom = true;
            }
        }
        if (!inRoom) {
            WebsocketManager.sendMessage(session, hashMap, username+"不在房间 [" + homeowner + "] 中");
            return;
        }

        hashMap.put("ROOM_MEMBERS",members);

        String message = "房间心跳检测";
        WebsocketManager.sendMessage(session, hashMap, message);

        // 心跳记录
        HeartBeatSchedule.addExistSession(username);
    }
}
